package com.hjxr.quota.sdoc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hjxr.quota.sdoc.domain.SdocColname;
import com.hjxr.quota.sdoc.mapper.SdocColnameMapper;
import com.hjxr.quota.sdoc.service.SdocColnameService;
import com.hjxr.quota.util.FileUtils;
import com.hjxr.sysadmin.security.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author ma
 * @date 2020/9/9 - 18:38
 **/
@Service
public class SdocColnameServiceImpl extends ServiceImpl<SdocColnameMapper, SdocColname> implements SdocColnameService {
    @Autowired
    private SdocColnameMapper sdocColnameMapper;
    @Autowired
    private TokenService tokenService;

    @Override
    public Boolean fieldsInformationToDb(String filePath, String fileName, Integer docId, HttpServletRequest request){
        int i = 0;
        SdocColname sdocColname = new SdocColname();
        try {
            for (String a : FileUtils.readFileHead(filePath, fileName)) {
                i++;
                sdocColname.setDocId(docId);
                if(a.startsWith("\"")&&a.endsWith("\"")){
                    a = a.substring(1,a.length());   //去掉第一个 "
                    a = a.substring(0,a.length()-1);  //去掉最后一个 "
                }
                sdocColname.setColumnName(a);
                if (FileUtils.isContainChinese(a)) {
                    sdocColname.setColumnCode(FileUtils.getPinYinHeadChar(a) + "_" + i);

                } else {
                    sdocColname.setColumnCode(a + "_" + i);
                }
                sdocColname.setColumnDescription("");
                sdocColname.setUpdateBy(tokenService.getLoginUser(request).getUsername());
                sdocColname.setUpdateDate(new Date());
                sdocColname.setOrderNum(i);
                sdocColname.setDataType("VARCHAR2");
                sdocColname.setColumnLength("200");
                save(sdocColname);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;

        }
        return true;
    }

    @Override
    public List<SdocColname> getListByDocId(Integer docId) {
        QueryWrapper<SdocColname> wrapper = new QueryWrapper<>();
        wrapper.eq("DOC_ID", docId);
        List<SdocColname> list = this.list(wrapper.orderByAsc("ORDER_NUM"));
        if (list == null) {
            list = new ArrayList<>();
        }
        return list;
    }

    @Override
    public int updateSdocCloname(SdocColname sdocColname) {
        return sdocColnameMapper.updateSdocCloname(sdocColname);
    }

}
